<?php

namespace app\admin\model\chase;

use think\Model;
use traits\model\SoftDelete;

class User extends Model
{

    use SoftDelete;

    

    // 表名
    protected $table = 'users';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'sex_text',
        'is_vip_text',
        'is_freeze_text',
        'ontime_text'
    ];
    

    
    public function getSexList()
    {
        return ['female' => __('Sex female'), 'male' => __('Sex male'), 'unknown' => __('Sex unknown')];
    }

    public function getIsVipList()
    {
        return ['no' => __('Is_vip no'), 'yes' => __('Is_vip yes')];
    }

    public function getIsFreezeList()
    {
        return ['no' => __('Is_freeze no'), 'yes' => __('Is_freeze yes')];
    }


    public function getSexTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['sex']) ? $data['sex'] : '');
        $list = $this->getSexList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getIsVipTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['is_vip']) ? $data['is_vip'] : '');
        $list = $this->getIsVipList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getIsFreezeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['is_freeze']) ? $data['is_freeze'] : '');
        $list = $this->getIsFreezeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getOntimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['ontime']) ? $data['ontime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setOntimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public static function getUserCount()
    {
        return self::count();
    }

    public static function getVipCount()
    {
        return self::where('vip', '<>', '')->count();
    }

    public static function getTodayUserCount()
    {
        return self::whereTime('createtime', 'today')->count();
    }

    public static function getTodayVipCount()
    {
        return self::whereTime('ontime', 'today')->count();
    }

    public function userCoupon()
    {
        return $this->hasMany(UserCoupon::class, 'user_id', 'id');
    }

    public function userVip()
    {
        return $this->hasOne(UserVip::class, 'name', 'vip');
    }

    public function merchant()
    {
        return $this->hasOne(Merchant::class, 'id', 'merchant_id');
    }

    public static function getByPhone($phone)
    {
        return self::where('phone', $phone)->find();
    }

}
